﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P58E42P3Controller : ControllerBase
    {


        [HttpPost]
        public ActionResult<MQResponse> ReleaseHF(dynamic objparam)
        {
            Log4Net.Debug(objparam);
            Console.WriteLine(objparam);
            //用了新的方式，哈哈方便多了
            P58E42P3param param = Common.JsonHelper.JsonToObject<P58E42P3param>(((Newtonsoft.Json.Linq.JObject)objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            string 丨丨丨;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }

                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"{DateTime.Now.ToString()} 按照HF单释放分货 {param.HFOrderNo} {param.Quantity}");
                #region 处理代码
                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    //returnControlIDs = "1[10,11,12,43,41]",
                    formName = "P58E42P3_W58E42P3A",
                    version = "MBR001",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                        //new FSREvent() { controlID="101", command ="SetControlValue",value=param.HFOrderNo },
                                        new FSREvent() { controlID="107", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P58E42P3_W58E42P3A",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E42P3_W58E42P3B"))
                {
                    JObject obj = response.ToJObject();

                    asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            //allowCache = true,
                            action = "execute",
                            actionRequest=new ActionRequest() {
                                formOID = "W58E42P3B",
                                formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                        new FSREvent() { controlID="101", command ="SetControlValue",value=param.HFOrderNo    },
                                        new FSREvent() { controlID="17", command="DoAction"  }
                                      }
                                  ),
                                  stopOnWarning = "false"
                            },
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    stackId = response.stackId;
                    stateId = response.stateId;
                    rid = response.rid;
                    if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E42P3_W58E42P3B"))
                    {
                        ///获取结果的总行数
                        obj = response.ToJObject();
                        int rowcount = Convert.ToInt32(obj["fs_P58E42P3_W58E42P3B"]["data"]["gridData"]["summary"]["records"]);
                        Console.WriteLine($"查询到{rowcount}条记录");
                        if (rowcount > 0)
                        {
                            List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                            List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                            int selectrowindex = -1;
                            gridcols.Add(new gridcolumnevent()
                            {
                                columnID = "50",
                                command = "SetGridCellValue",
                                value = param.Quantity.ToString()
                            });
                            for (int i = 0; i < rowcount; i++)
                            {
                                //string hfpdate = Convert.ToDateTime(obj["fs_P58E42P3_W58E42P3B"]["data"]["gridData"]["rowset"][i]["z_DRQJ_47"]["value"].ToString()).ToString("yyyyMMdd");
                                string lineno = obj["fs_P58E42P3_W58E42P3B"]["data"]["gridData"]["rowset"][i]["z_LNID_41"]["value"].ToString().Replace(".", "");

                                if (param.lineno == lineno)
                                {
                                    Console.WriteLine($"正在处理第{i}行  HF单行号{lineno}");
                                    stackId = response.stackId;
                                    stateId = response.stateId;
                                    int rowindex = Convert.ToInt32(obj["fs_P58E42P3_W58E42P3B"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                                    gridrows.Add(new gridrowupdateevents()
                                    {
                                        gridColumnEvents = gridcols,
                                        rowNumber = rowindex
                                    });
                                    selectrowindex = i;
                                }
                            }

                            if (selectrowindex == -1)
                                throw new MQException("404",$"未找到行号{param.lineno} 的HF单信息{param.HFOrderNo}");


                            ActionRequest actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W58E42P3B",
                                formActions = new FormActionsCollection
                                         (
                                             new FSREvent[]
                                             {
                                            new FSREvent() { controlID=$"1.{selectrowindex}", command="SelectRow" ,
                                                    gridAction =new GridAction(){gridID="1",gridRowUpdateEvents=gridrows}
                                                    },
                                            new FSREvent() { controlID="12", command="DoAction"  }
                                             }
                                         )
                                     ,
                                stopOnWarning = "false"
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            needclose = true;
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                           
                            if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E42P3_W58E42P3A"))
                            {
                                //Console.WriteLine(response.JsonString);
                                Console.WriteLine($"{DateTime.Now.ToString()} {param.HFOrderNo}释放完成:{param.PromisedDeliveryDate}  {response.currentApp}");
                                obj = response.ToJObject();
                                //应该查询到数据
                                //string NAno = obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["rowset"]["0"]["z_DOCO_45"].ToString();
                                execresult.Result = param.HFOrderNo;
                                execresult.Message = response.JsonString;
                                Log4Net.Info(response.JsonString);
                            }
                        }
                        else
                            throw new MQException("404",$"找不到HF{param.HFOrderNo}分货记录，请检查是否已输入分货比例");
                    }
                }
                #endregion
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W58E42P3B"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }
            return execresult;
        }





    }
}